package cn.com.fstar.framework.admin.service;

import cn.com.fstar.core.CodeConstant;
import cn.com.fstar.core.model.Tdictionary;
import cn.com.fstar.core.pageModel.Dictionary;
import cn.com.fstar.core.pageModel.Tree;
import cn.com.fstar.framework.base.dao.BaseDaoI;
import cn.com.fstar.framework.base.model.EasyUIComboTree;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 
 * @author
 * 
 */
@Service
public class DictionaryService {

    private static final Logger LOG = Logger.getLogger(DictionaryService.class);

    @Autowired
    private BaseDaoI<Tdictionary> dictionaryDao;

    public List<Dictionary> dictionaryDataGrid(Dictionary dictionary) {
        String hql = " from Tdictionary t order by t.dictSort asc ";
        List<Dictionary> list = new ArrayList<Dictionary>();
        List<Tdictionary> listt = dictionaryDao.find(hql);
        if (listt != null && listt.size() > 0) {
            for (Tdictionary tAdmDictionary : listt) {
                Dictionary ad = new Dictionary();
                BeanUtils.copyProperties(tAdmDictionary, ad);
                list.add(ad);
            }         
        }
        return list;
    }

    public String add(Dictionary dictionary) throws Exception {

        String msg = "";
        // 判断字典编号是否存在
        if (dictionary.getPid() == null || "".equals(dictionary.getPid())) {
            dictionary.setPid("0");
        }
        Map<String, Object> paramCode = new HashMap<String, Object>();
        paramCode.put("dictCode", dictionary.getDictCode().trim());
        if (dictionaryDao.count("select count(*) from Tdictionary t where t.dictCode = :dictCode", paramCode) > 0) {
            msg = "zdCodeExist";
        } else {
            // 保存TAdmDictionary
            Tdictionary t = new Tdictionary();
            BeanUtils.copyProperties(dictionary, t);
            dictionaryDao.save(t);
            msg = "success";
        }

        return msg;
    }

    public String edit(Dictionary dictionary) throws Exception {

        String msg = "";
        if (dictionary.getPid() == null || "".equals(dictionary.getPid())) {
            dictionary.setPid("0");
        }
        // 判断字典编号是否存在
        Map<String, Object> paramCode = new HashMap<String, Object>();
        paramCode.put("id", dictionary.getId().trim());
        paramCode.put("dictCode", dictionary.getDictCode().trim());
        if (dictionaryDao.count("select count(*) from Tdictionary t where t.dictCode = :dictCode and t.id != :id",
                paramCode) > 0) {
            msg = "zdCodeExist";
        } else {
            // 判断字典名称是否存在
            Map<String, Object> paramName = new HashMap<String, Object>();
            paramName.put("id", dictionary.getId().trim());
            paramName.put("dictName", dictionary.getDictName().trim());
            if (dictionaryDao.count("select count(*) from Tdictionary t where t.dictName = :dictName and t.id != :id",
                    paramName) > 0) {
                msg = "zdNameExist";
            } else {
                // 保存TAdmDictionary
                Tdictionary t = new Tdictionary();
                BeanUtils.copyProperties(dictionary, t);
                // t.setTAdmDictionaryType(tdictionaryType);
                dictionaryDao.update(t);
                msg = "success";
            }
        }

        return msg;
    }

    /**
     * 获取文件分类 树列表
     *
     * @return
     */
    public List<EasyUIComboTree> dictionarysComboTree() {

        List<EasyUIComboTree> dictionaryList = new ArrayList<EasyUIComboTree>();

        String sql = " from Tdictionary t order by t.dictSort asc ";

        List<Tdictionary> list = dictionaryDao.find(sql);

        if (list != null && list.size() > 0) {

            Set<String> hs = new HashSet<String>();
            for (Tdictionary r : list) {
                hs.add(r.getDictPid());
            }

            for (int i = 0; i < list.size(); i++) {
                Tdictionary Tdictionary = list.get(i);

                EasyUIComboTree tree = new EasyUIComboTree();
                tree.setId(Tdictionary.getId());
                tree.setText(Tdictionary.getDictName());
                if (null != Tdictionary.getDictPid()) {
                    tree.setPid(Tdictionary.getDictPid());
                    if ("0".equals(Tdictionary.getDictPid()) && hs.contains(Tdictionary.getId())) {
                        tree.setState("closed");
                    }
                }
                dictionaryList.add(tree);
            }
        }
        return dictionaryList;
    }

    /**
     * 获取文件分类 树列表
     *
     * @return
     */
    public List<EasyUIComboTree> libComboTree() {

        List<EasyUIComboTree> dictionaryList = new ArrayList<EasyUIComboTree>();

        String sql = " from Tdictionary t order by t.dictSort asc ";

        List<Tdictionary> list = dictionaryDao.find(sql);

        if (list != null && list.size() > 0) {

            Set<String> hs = new HashSet<String>();
            for (Tdictionary r : list) {
                hs.add(r.getDictPid());
            }
            for (int i = 0; i < list.size(); i++) {
                Tdictionary Tdictionary = list.get(i);
                if (Tdictionary.getDictCode().lastIndexOf("00") > 0 && Tdictionary.getDictCode().length() > 6) {
                    EasyUIComboTree tree = new EasyUIComboTree();
                    tree.setId(Tdictionary.getDictCode());
                    tree.setText(Tdictionary.getDictName());
                    if (null != Tdictionary.getDictPid()) {
                        tree.setPid(Tdictionary.getDictPid());
                        if ("0".equals(Tdictionary.getDictPid()) && hs.contains(Tdictionary.getId())) {
                            tree.setState("closed");
                        }
                    }
                    dictionaryList.add(tree);
                }
            }
        }
        return dictionaryList;
    }

    /**
     * 删除字典项
     * 
     * @param id
     * @return
     */
    public String deleteDictionary(String id, String parentId) {
        String msg = "";
        if (parentId == null || parentId.equals("") || parentId.equals("null")) {// 字典类型数据
            Tdictionary ty = dictionaryDao.get(Tdictionary.class, id);

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("pid", id);
            List<Tdictionary> list = dictionaryDao.find(" from Tdictionary t where t.pid=:pid", params);
            if (list != null && list.size() > 0) {
                for (Tdictionary tAdmDictionary : list) {
                    dictionaryDao.delete(tAdmDictionary);
                }
            }
            dictionaryDao.delete(ty);
        } else {
            Tdictionary t = dictionaryDao.get(Tdictionary.class, id);
            dictionaryDao.delete(t);
        }
        msg = "success";
        return msg;

    }

    /**
     * 根据ID获得对象
     * 
     * @param id
     * @return
     */
    public Dictionary getDictionary(String id, String parentId) {
        Dictionary dictionary = new Dictionary();

        Tdictionary Tdictionary = dictionaryDao.get(Tdictionary.class, id);
        BeanUtils.copyProperties(Tdictionary, dictionary);
        dictionary.setParentId(parentId);

        return dictionary;
    }

    /**
     * 获取所有的字典数据
     * 
     * @author lihf
     * @date 2015年12月3日 下午4:13:13
     * @return
     * @throws Exception
     */
    public Map<String, List<Dictionary>> getDictionaryByAll() throws Exception {
        Map<String, List<Dictionary>> dictMap = new HashMap<String, List<Dictionary>>();
        String hql = "from Tdictionary t order by t.dictSort asc ";
        List<Tdictionary> tList = dictionaryDao.find(hql);
        for (Tdictionary t : tList) {
            if ("0".equalsIgnoreCase(t.getDictPid())) {
                List<Dictionary> subdictList = new ArrayList<Dictionary>();
                for (Tdictionary subTdict : tList) {
                    if (subTdict.getDictPid().equalsIgnoreCase(t.getId())) {
                        Dictionary subdict = new Dictionary();
                        BeanUtils.copyProperties(subTdict, subdict);
                        subdictList.add(subdict);
                    }
                }
                dictMap.put(t.getDictCode(), subdictList);
            }
        }
        return dictMap;
    }

    /**
     * 根据字典编码获取所有的字典数据
     * 
     * @author lihf
     * @date 2015年12月11日 下午4:43:26
     * @param dictCode
     * @return
     * @throws Exception
     */
    public Dictionary getDictionaryByDictCode(String dictCode) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dictCode", dictCode);
        String hql = " from Tdictionary t where 1=1 and t.dictCode=:dictCode ";
        Dictionary dict = new Dictionary();
        Tdictionary t = dictionaryDao.get(hql, params);
        if (null != t) {
            BeanUtils.copyProperties(t, dict);
        }
        return dict;
    }

    /**
     * 根据字典名称获取所有的字典数据
     * 
     * @author lihf
     * @date 2015年12月11日 下午4:43:26
     * @param
     * @return
     * @throws Exception
     */
    public Dictionary getDictionaryByDictName(String dictName) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dictName", dictName);
        String hql = " from Tdictionary t where 1=1 and t.dictName=:dictName ";
        Dictionary dict = new Dictionary();
        Tdictionary t = dictionaryDao.get(hql, params);
        if (null != t) {
            BeanUtils.copyProperties(t, dict);
        }
        return dict;
    }

    /**
     * 加载数据字典
     * 
     * @author lxq 2015-03-18
     * @return
     */
    public Map<String, List<Dictionary>> getDictionaryInfo() {
        Map<String, List<Dictionary>> dictionaryMap = new HashMap<String, List<Dictionary>>();

        String hql = "from Tdictionary t where t.pid='0'";

        List<Tdictionary> listTtictionary = dictionaryDao.find(hql);

        try {
            if (listTtictionary != null && listTtictionary.size() > 0) {
                for (Tdictionary tdictionaryType : listTtictionary) {

                    String sicTypeCode = tdictionaryType.getDictCode();
                    List<Dictionary> listDic = null;
                    if ("libCode".equals(tdictionaryType.getDictCode())) {
                        listDic = this.getByCode();
                    } else if ("areaCode".equals(tdictionaryType.getDictCode())) {
                        listDic = this.getByCode();
                    } else {
                        listDic = this.getByPid(tdictionaryType.getId());
                    }
                    if (listDic != null && listDic.size() > 0) {
                        dictionaryMap.put(sicTypeCode, listDic);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return dictionaryMap;
    }


    /**
     * 根据父ID查找字典列表
     * 
     * @author lihf
     * @date 2016年1月14日 上午9:31:46
     * @param pid
     * @return
     * @throws Exception
     */
    public List<Dictionary> getByPid(String pid) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pid", pid);
        params.put("id", pid);
        String hql = " from Tdictionary t where t.id=:id or t.pid = :pid order by t.dictCode asc";
        List<Tdictionary> list = dictionaryDao.find(hql, params);
        List<Dictionary> lista = null;
        if (list != null && list.size() > 0) {
            lista = new ArrayList<Dictionary>();
            for (Tdictionary admDictionarys : list) {
                Dictionary admDictionary = new Dictionary();
                BeanUtils.copyProperties(admDictionarys, admDictionary);
                lista.add(admDictionary);

            }
        }
        return lista;
    }

    private List<Dictionary> getByCode() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("code", "33%");
        String hql = " from Tdictionary t where t.dictCode like :code order by t.dictCode asc";
        List<Tdictionary> list = dictionaryDao.find(hql, params);
        List<Dictionary> lista = new ArrayList<Dictionary>();
        if (list != null && list.size() > 0) {
            for (Tdictionary admDictionarys : list) {
                Dictionary admDictionary = new Dictionary();
                BeanUtils.copyProperties(admDictionarys, admDictionary);
                lista.add(admDictionary);
            }
            return lista;
        }
        return null;
    }

    /**
     * 根据字典编码获取字典树
     * 
     * @author lihf
     * @date 2016年2月18日 下午3:00:10
     * @param dictCode
     * @return
     * @throws Exception
     */
    public List<Tree> getDictTreeListByDictCode(String dictCode) throws Exception {
        List<Tree> listTree = new ArrayList<Tree>();
        Dictionary dict = getDictionaryByDictCode(dictCode);
        if (null == dict) {
            return listTree;
        }
        List<Dictionary> dictList = getByPid(dict.getId());
        if (null != dictList && dictList.size() > 0) {
            for (Dictionary admDictionary : dictList) {
                setTree(admDictionary, listTree);
            }
        }
        return listTree;
    }

    private void setTree(Dictionary dict, List<Tree> listTree) {
        try {
            Tree tree = new Tree();
            BeanUtils.copyProperties(dict, tree);
            // tree.setId(dict.getDictCode());
            tree.setCode(dict.getDictCode());
            tree.setText(dict.getDictName());
            // tree.setPid(dict.getPid());
            List<Dictionary> dictList = getByPid(dict.getId());
            if (null != dictList && dictList.size() > 0) {
                tree.setState("closed");
                for (Dictionary admDictionary : dictList) {
                    setTree(admDictionary, listTree);
                }
            }
            listTree.add(tree);

        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }

    public List<EasyUIComboTree> libCodeComboTree() {

        List<EasyUIComboTree> dictionaryList = new ArrayList<EasyUIComboTree>();
        String sql = " from Tdictionary t order by t.dictCode asc ";

        List<Tdictionary> list = dictionaryDao.find(sql);

        if (list != null && list.size() > 0) {

            Set<String> hs = new HashSet<String>();
            for (Tdictionary r : list) {
                hs.add(r.getDictPid());
            }
            for (int i = 0; i < list.size(); i++) {
                Tdictionary Tdictionary = list.get(i);
                if (Tdictionary.getDictCode().lastIndexOf("00") > 0 && Tdictionary.getDictCode().length() != 6) {
                    EasyUIComboTree tree = new EasyUIComboTree();
                    tree.setId(Tdictionary.getDictCode());
                    tree.setText(Tdictionary.getDictName());
                    if (null != Tdictionary.getDictPid()) {
                        tree.setPid(Tdictionary.getDictPid());
                        if ("0".equals(Tdictionary.getDictPid()) && hs.contains(Tdictionary.getId())) {
                            tree.setState("closed");
                        }
                    }
                    dictionaryList.add(tree);
                }
            }
        }
        return dictionaryList;
    }

    public List<EasyUIComboTree> stateCodeComboTree() {

        List<EasyUIComboTree> dictionaryList = new ArrayList<EasyUIComboTree>();
        for (int i = 0; i < 2; i++) {
            EasyUIComboTree tree = new EasyUIComboTree();
            tree.setId(String.valueOf(i));
            tree.setText(i == 0 ? CodeConstant.NOMAL : CodeConstant.CONNECT_OFF);
            dictionaryList.add(tree);
        }
        return dictionaryList;
    }

    /***
     * 只根据dictName获取字典信息
     * 
     * @param
     * @param dictName
     * @return
     */
    public Dictionary getByAreaName(String dictName) {
        // 如果字典描述信息或者字典名称都没有，直接返回
        if (StringUtils.isBlank(dictName))
            return null;

        StringBuilder hql = new StringBuilder();
        hql.append("from Tdictionary t where 1=1 ");

        if (StringUtils.isNotBlank(dictName)) {
            hql.append(" and t.dictName like'%");
            hql.append(dictName + "%' ");
            hql.append(" and substring(t.dictCode,7,9)='000'");

        }
        Tdictionary tadmDictionary = dictionaryDao.get(hql.toString());
        Dictionary admDictionary = new Dictionary();
        if (tadmDictionary != null)
            BeanUtils.copyProperties(tadmDictionary, admDictionary);

        return admDictionary;
    }

}
